/* 
 * Document   : cubemarketing-script
 * Created on : 15 mai 2013, 09:23:43
 * Author     : Mamy RAKOTONIRINA
 * Description: JS for Cubemarketing
 */


$(document).ready(function() {
    var navIdx = 1;
    var uri = document.location.pathname; 
    var icons = {
        header: "ui-icon-carat-1-e",
        activeHeader: "ui-icon-carat-1-s"
    };
    
    if(uri.match(/marche/)){
        navIdx = 0;
    }
    
    $( "#nav-cube" ).accordion({
        icons: icons,
        active: navIdx,
        heightStyle: "content"
    });
    
    $( "#rubrique" ).buttonset();
    
    $( "#tabs" ).tabs();
    
    $("#tree").treeview({
        collapsed: true,
        animated: "medium",
        control:"#sidetreecontrol",
        persist: "location"
    });
    
    $(".datepicker").datepicker({
        maxDate: '+0D', 
        dateFormat: 'dd/mm/yy', 
        altFormat: "yy-mm-dd",
        altField: '#altDate',
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], 
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
        monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Août','Sep','Oct','Nov','Déc'], 
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
        prevText: 'Précédent', 
        nextText: 'Suivant'	
    });
    
    $("#startDate").datepicker({
        maxDate: '+0D',
        dateFormat: 'dd/mm/yy', 
        altFormat: "yy-mm-dd",
        altField: '#altStartDate',
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], 
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
        monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Août','Sep','Oct','Nov','Déc'], 
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
        prevText: 'Précédent', 
        nextText: 'Suivant'
    });
    
    $("#endDate").datepicker({
        maxDate: '+0D',
        dateFormat: 'dd/mm/yy', 
        altFormat: "yy-mm-dd",
        altField: '#altEndDate',
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], 
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
        monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Août','Sep','Oct','Nov','Déc'], 
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
        prevText: 'Précédent', 
        nextText: 'Suivant'
    });
    
    // Start script for rotate
    var rotate_container = $(".perimetre-title");            
    rotate_container.each(function(){
        var hisRotate = $(this).find('.rotate');
        var hisRotateWidth = hisRotate.width();

        $(this).height(hisRotateWidth);
        hisRotate.width(30);
    });
    // End script for rotate
            
    var checkboxHeight = "16";
    var radioHeight = "16";
    var Custom = {
	init: function() {
            var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
            for(var a = 0; a < inputs.length; a++) {
                if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
                    span[a] = document.createElement("span");
                    span[a].className = inputs[a].type;

                    if(inputs[a].checked == true) {
                        if(inputs[a].type == "checkbox") {
                            var position = "0 -" + (checkboxHeight) + "px";
                            span[a].style.backgroundPosition = position;
                        } else {
                            var position = "0 -" + (radioHeight) + "px";
                            span[a].style.backgroundPosition = position;
                        }
                    }
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    inputs[a].onchange = Custom.clear;
                    if(!inputs[a].getAttribute("disabled")) {
                        span[a].onmousedown = Custom.pushed;
                        span[a].onmouseup = Custom.check;
                    } else {
                        span[a].className = span[a].className += " disabled";
                    }
                }
            }
            inputs = document.getElementsByTagName("select");
            for(var a = 0; a < inputs.length; a++) {
                if(inputs[a].className == "styled") {
                    option = inputs[a].getElementsByTagName("option");
                    active = option[0].childNodes[0].nodeValue;
                    textnode = document.createTextNode(active);
                    for(var b = 0; b < option.length; b++) {
                        if(option[b].selected == true) {
                            textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                        }
                    }
                    span[a] = document.createElement("span");
                    span[a].className = "select";
                    span[a].id = "select" + inputs[a].name;
                    span[a].appendChild(textnode);
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    if(!inputs[a].getAttribute("disabled")) {
                        inputs[a].onchange = Custom.choose;
                    } else {
                        inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
                    }
                }
            }
            document.onmouseup = Custom.clear;
	},
	pushed: function() {
            var element = this.nextSibling;
            if(element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 0";
            } else if(element.checked == true && element.type == "radio") {
                this.style.backgroundPosition = "0 0";
            } else if(element.checked != true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
            } else {
                this.style.backgroundPosition = "0 -" + radioHeight + "px";
            }
	},
	check: function() {
            var element = this.nextSibling;
            if(element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 0";
                //element.checked = false;
                //$(element).checked(false);
                element.prop('checked', false);
            } else {
                if(element.type == "checkbox") {
                    this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
                } else {
                    this.style.backgroundPosition = "0 -" + radioHeight + "px";
                    var group = this.nextSibling.name;
                    var inputs = document.getElementsByTagName("input");
                    for(var a = 0; a < inputs.length; a++) {
                        if(inputs[a].name == group && inputs[a] != this.nextSibling) {
                            inputs[a].previousSibling.style.backgroundPosition = "0 0";
                        }
                    }
                }
                //element.checked = true;
                //$(element).checked(true);
                element.prop('checked', true);
            }
	},
	clear: function() {
            var inputs = document.getElementsByTagName("input");
            for(var b = 0; b < inputs.length; b++) {
                if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight + "px";
                } else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight + "px";
                } else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                }
            }
	},
	choose: function() {
            var option = this.getElementsByTagName("option");
            for(var d = 0; d < option.length; d++) {
                if(option[d].selected == true) {
                    document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
                }
            }
	}
    };
    window.onload = Custom.init;
});

$.event.special.hoverintent = {
    setup: function() {
        $( this ).bind( "mouseover", jQuery.event.special.hoverintent.handler );
    },
    teardown: function() {
        $( this ).unbind( "mouseover", jQuery.event.special.hoverintent.handler );
    },
    handler: function( event ) {
        var currentX, currentY, timeout,
            args = arguments,
            target = $( event.target ),
            previousX = event.pageX,
            previousY = event.pageY;
    
        function track( event ) {
            currentX = event.pageX;
            currentY = event.pageY;
        };
        
        function clear() {
            target
                .unbind( "mousemove", track )
                .unbind( "mouseout", clear );
            clearTimeout( timeout );
        }
        function handler() {
            var prop,
                orig = event;
        
            if ( ( Math.abs( previousX - currentX ) +
            Math.abs( previousY - currentY ) ) < 7 ) {
                clear();
                event = $.Event( "hoverintent" );
                for ( prop in orig ) {
                    if ( !( prop in event ) ) {
                        event[ prop ] = orig[ prop ];
                    }
                }
                delete event.originalEvent;
                target.trigger( event );
            } else {
                previousX = currentX;
                previousY = currentY;
                timeout = setTimeout( handler, 100 );
            }
        }
        timeout = setTimeout( handler, 100 );
        target.bind({
        mousemove: track,
        mouseout: clear
        });
    }
};

function listbox_selectall(listID, isSelect) {
    var listbox = document.getElementById(listID);
    for(var count=0; count < listbox.options.length; count++) {
        listbox.options[count].selected = isSelect;
    }
}

function listbox_moveacross(sourceID, destID) {
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);
    
    for(var count=0; count < src.options.length; count++) {
        if(src.options[count].selected == true) {
            var option = src.options[count];
            var newOption = document.createElement("option");
            newOption.value = option.value;
            newOption.text = option.text;
            newOption.selected = true;
            try {
                dest.add( newOption, null); //Standard
                src.remove(count, null);
            }catch(error) {
                dest.add( newOption); //Standard
                //dest.add(newOption); // IE only
                src.remove(count);
            }
            count--;
        }
    }
}

function listbox_moveselected(sourceID, destID) {
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);
    
//    for (var i=0; i<dest.length; i++) {
//        dest.removeChild(dest[i]);
//    }

    var option = src.options[src.selectedIndex];
    var newOption = document.createElement("option");
    newOption.value = option.value;
    newOption.text = option.text;
    newOption.selected = true;
    try {
        dest.add( newOption, null); //Standard
        src.remove(src.selectedIndex);
    }catch(error) {
        dest.add( newOption); //Standard
        src.remove(src.selectedIndex);
    }
}

function sortlist(mylist) {
    var lb = document.getElementById(mylist);
    var arrTexts = new Array();
    
    for(i=0; i<lb.length; i++)  {
        arrTexts[i].text = lb.options[i].text;
        arrTexts[i].value = lb.options[i].value;
    }
    
    arrTexts.sort();
    
    for(i=0; i<lb.length; i++)  {
        lb.options[i].text = arrTexts[i].text;
        lb.options[i].value = arrTexts[i].value;
    }
}

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

function dateToDMY(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '/' + (m<=9 ? '0' + m : m) + '/' + y;
}

function submitForm(){
    // Manage Uri
    var uri = document.location.pathname;
    var operationtestPos = uri.lastIndexOf("operationtest");
    var resteUri = uri.substring(operationtestPos,100);
    var operationtestUri = uri.replace(resteUri, "operationtest");
    
    var radioValue = $("input[name=rubrique]:checked").val();    
    var listbox = document.getElementById('selectable');
    
    if(listbox.value == ''){
        $('.select-wrapper').effect("shake", "fast");
    } else {    
        if(radioValue == 1) {
            $("#op-form").attr("action", operationtestUri+'/tableaudebord');
        } else if(radioValue == 2) {
            $("#op-form").attr("action", operationtestUri+'/synthese');
        } else if(radioValue == 3){
            $("#op-form").attr("action", operationtestUri+'/pilotage');
        }
        
        $("#op-form").submit();
    }
}

function cDelete(id){
    // Manage Uri
    var uri = document.location.pathname;
    
    if(confirm('Voulez vous vraiment supprimé?')){
        window.location.href = uri+'/delete/'+id;
    }
}

function attribStore(id){
    // Manage Uri
    var uri = document.location.pathname;
    
    window.location.href = uri+'/attribstore/'+id;
}

function otherCancel(controller){
    // Get foamUri
    var uri = document.location.pathname;
    var operationtestPos = uri.lastIndexOf("operationtest");
    var resteUri = uri.substring(operationtestPos,100);
    var operationtestUri = uri.replace(resteUri, "operationtest");
    
    window.location.href = operationtestUri+'/'+controller; 
}

function multiSelectAll(choice) {
    $('.selectable').multiSelect(choice);
    return false;
}

function showRubrique(el){
    var chk = $(el).children('input');
    var chkId = chk.attr('id');
    var wrc = $('.right-content').width()-38;        
    $('.pc-content').css('max-width',wrc);
    if(chk.is(':checked')){
        $('.'+chkId).fadeIn(1000);
    } else { 
        $('.'+chkId).fadeOut(500);
    }
}

function showSGRubrique(el){
    var chk = $(el).children('input');
    var chkId = chk.attr('id');
    var wrc = $('.right-content').width()-38;        
    $('.pc-content').css('max-width',wrc);
    if(chk.is(':checked')){
        $('.'+chkId).fadeIn(1000);
        $('p.'+chkId).fadeIn(1000);
    } else { 
        $('.'+chkId).fadeOut(500);
        $('p.'+chkId).fadeOut(500);
    }
}

function showSDRubrique(el){
    var chk = $(el).children('input');
    var chkId = chk.attr('id');
    var wrc = $('.right-content').width()-38;        
    $('.pc-content').css('max-width',wrc);
    if(chk.is(':checked')){
        $('tr.'+chkId).fadeIn(1000);
    } else { 
        $('tr.'+chkId).fadeOut(500);
    }
}

function showSDRubrique_old(el){
    var allRub = $(".pc-head2").find(':checkbox'); 
    var chk = $(el).children('input');
    var chkId = chk.attr('id');
    var wrc = $('.right-content').width()-38;        
    $('.pc-content').css('max-width',wrc);
    if(chk.is(':checked')){
        // Disabled other checkbox
        allRub.prop('checked', false);
        allRub.each(function(){
            var rubId = $(this).attr('id');
            $('.'+rubId).hide();
        }); 
        
        // Enabled this checkbox
        chk.prop('checked', true);
        $('.'+chkId).show();
    } else { 
        // Disabled all checkbox
        allRub.prop('checked', false);
        allRub.each(function(){
            var rubId = $(this).attr('id');
            $('.'+rubId).hide();
        }); 
    }
}

function showSRPCRubrique(el){
    // Get operationtestUri
    var uri = document.location.pathname;
    var operationtestPos = uri.lastIndexOf("operationtest");
    var resteUri = uri.substring(operationtestPos,100);
    var operationtestUri = uri.replace(resteUri, "operationtest");
    var baseUri = uri.replace(resteUri, "");
    var allRub = $(".pc-head3 .choice").find(':checkbox'); 
    var chk = $(el).children('input');
    var chkId = chk.attr('id');
    
    if(chkId == 'qte3'){
        var uri = operationtestUri+'/synthese/rapportproduit';
    } else if(chkId == 'cattc3'){
        var uri = operationtestUri+'/synthese/rapportproduit2';
    } else if(chkId == 'caht3'){
        var uri = operationtestUri+'/synthese/rapportproduit3';
    } 
    
    if(chk.is(':checked')){
        // Disabled other checkbox
        allRub.prop('checked', false);
        
        // Enabled this checkbox
        chk.prop('checked', true);
        $('#tabs-rapport').html('<p class="loading" style="text-align: center; margin: 20px;"><img src="'+baseUri+'/img/operationtest/loader.gif" alt="loading" /></p>');
        $.ajax({
            type: 'POST',
            url: uri,
            dataType: "html",
            cache: false,
            success: function(contenu){
                $('#tabs-rapport').html(contenu);
            }
        });
    } else { 
        // Disabled all checkbox
        allRub.prop('checked', false);
        $('#tabs-rapport').empty();
    }
}

function changeRapportContent() {
    // Get foamUri
    var uri = document.location.pathname;
    var foamPos = uri.lastIndexOf("operationtest");
    var resteUri = uri.substring(foamPos,100);
    var foamUri = uri.replace(resteUri, "operationtest");    
    
    $('#tabs-rapport .loading').show();
    $('p.accessrapport, div.accessrapportbutton').hide();
    
    $.ajax({
        type: 'POST',
        url: foamUri+'/synthese/rapportproduit',
        dataType: "html",
        cache: false,
        success: function(contenu){        
            $("#tabs-rapport").fadeOut(500);
            $("#tabs-rapport").empty();
            $("#tabs-rapport").html(contenu);
            $('#tabs-rapport .loading').hide();
            $("#tabs-rapport").fadeIn(500);
            var wrc = $('.right-content').width()-38;        
            $('.pc-content').css('max-width',wrc);
        }
    }); 
}

function checkStore(el) {
    var chk = $(el).children('input');
    var chkId = chk.attr('id');
    
    if(chk.is(':checked')){
        $('.'+chkId+' :checkbox').prop('checked', false);
    } else { 
        $('.'+chkId+' :checkbox').prop('checked', true);
    }
}

function uncheckAll() {
    var chk = $('.allrbq').find(':checkbox');
    chk.each(function(){
       var chkId = $(this).attr('id');
       $('.'+chkId).fadeOut('fast');
       $(this).prop('checked', false);
    });
    $('#uncheckall').prop('checked', false);
}

function uncheckAll2() {
    var chk = $('.allrbq2').find(':checkbox');
    chk.each(function(){
       var chkId = $(this).attr('id');
       $('.'+chkId).fadeOut('fast');
       $(this).prop('checked', false);
    });
    $('#uncheckall2').prop('checked', false);
}

function uncheckAll3() {
    var chk = $('.allrbq3').find(':checkbox');
    chk.each(function(){
       var chkId = $(this).attr('id');
       $('.'+chkId).fadeOut('fast');
       $(this).prop('checked', false);
    });
    $('#uncheckall3').prop('checked', false);
}

